package org.outlook.apps.goal.ui;

import java.awt.AWTException;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;

import org.outlook.apps.goal.action.Authenticater;
import org.outlook.apps.goal.pojo.Goal;
import org.outlook.apps.goal.ui.components.GoalListPopupMenu;
import org.outlook.apps.goal.ui.components.login.LoginDialog;
import org.outlook.apps.lunar.LunarUI;
import org.outlook.commons.io.ResourceUtil;
import org.outlook.commons.pojo.Globals;

import com.sun.awt.AWTUtilities;

public class MainUI {
	
	private TrayIcon trayIcon;
	private MenuItem exitTrayBt;
	private MenuItem configBt;
	private JFrame frame;
	private Vector<Goal> goals;
	private MenuItem viewBt;
	private ViewUI viewer;
	private ConfigUI config;
	private LoginDialog loginUI;
	private JList list;
	private MenuItem lunarBt;
	private MenuItem webInfoBt;
	private MenuItem privateBt;
	
	public MainUI() {
		super();
		if (SystemTray.isSupported()) {
			SystemTray tray = SystemTray.getSystemTray();
			final URL resourceInClasspath = ResourceUtil.getResourceInClasspath("/images/logo.png");
//			System.out.println(resourceInClasspath);
			Image logo = Toolkit.getDefaultToolkit().getImage(resourceInClasspath);
			lunarBt = new MenuItem("Lunar calendar");
			webInfoBt = new MenuItem("Web Info Box");
			privateBt = new MenuItem("Private");
			viewBt = new MenuItem("View my Bussines");
			configBt = new MenuItem("Config");
			exitTrayBt = new MenuItem("Exit");
			PopupMenu popupMenu = new PopupMenu();
			popupMenu.add(lunarBt);
			popupMenu.add(webInfoBt);
			popupMenu.addSeparator();
			popupMenu.add(privateBt);
			popupMenu.add(viewBt);
			popupMenu.add(configBt);
			popupMenu.add(exitTrayBt);
			trayIcon = new TrayIcon(logo, "Goal", popupMenu);
			try {
				tray.add(trayIcon);
			} catch (AWTException e) {
			}

			attachActionListener(Boolean.FALSE);
		}
	}

	private void attachActionListener(Boolean global) {
		if(!global) {
			if(isFirstTime()) 
				showUpConfig();
			trayIcon.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					if (e.getClickCount() == 2) {
						displayGoals(true);
					}
				}

				@Override
				public void mousePressed(MouseEvent e) {
					super.mousePressed(e);
				}
			});

			exitTrayBt.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
						System.exit(0);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			});

			configBt.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					authenticate();
					displayConfig();
				}
			});
			
			viewBt.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					displayView();
				}
			});

			lunarBt.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					LunarUI.startup();
				}
			});
			
			webInfoBt.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					
				}
			});
			
			privateBt.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					
				}
			});
		}
	}

	private void authenticate() {
		if(Authenticater.isRequireLogin()) {
			displayLoginForm();
//			checkAuthentication();
		}
	}

	private void showUpConfig() {
		// TODO Auto-generated method stub
		
	}

	private boolean isFirstTime() {
		// TODO Auto-generated method stub
		return false;
	}

	protected void displayLoginForm() {
		if(loginUI == null) {
//			loginUI = new LoginUI(frame);
			loginUI = new LoginDialog();
		} else 
			loginUI.setVisible(Boolean.TRUE);
	}

	private void displayView() {
		if(viewer == null) {
			viewer = new ViewUI();
			new Thread(viewer).start();
		} else
			viewer.setVisible(Boolean.TRUE);
	}

	private void displayConfig() {
		if(config == null) {
			config = new ConfigUI();
			new Thread(config).start();
		} else
			config.setVisible(Boolean.TRUE);
	}

	private void displayGoals(boolean b) {
		if(frame != null) {
			frame.setVisible(Boolean.TRUE);
			return ;
		}
		JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
		frame = new JFrame();

		Component goalListComponent = renderGoalList();
		frame.add(goalListComponent);

		frame.setAlwaysOnTop(Boolean.TRUE);
		frame.setPreferredSize(new Dimension(150,32*goals.size()+35));
		findBestLocation();
		frame.setVisible(Boolean.TRUE);
		frame.pack();
		AWTUtilities.setWindowOpacity(frame, 0.37f);
//		AWTUtilities.setWindowShape(this, arg1)
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setResizable(Boolean.FALSE);
	}

	private void findBestLocation() {
		int x = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() - 200);
		int y = 50;
		if(frame.getPreferredSize().getHeight()<100)
			y = (int) frame.getPreferredSize().getHeight();
		frame.setLocation(x, y);
	}

	private Component renderGoalList() {
		goals = getGoalList();
		list = new JList(goals) {

			private static final long serialVersionUID = 1L;

			@Override
			public String getToolTipText(MouseEvent event) {
				int index = locationToIndex(event.getPoint());
				setSelectedIndex(index);
				return goals.get(index).getDescription();
			}
			
		};
		list.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		final GoalListPopupMenu menu = new GoalListPopupMenu("PopupInList");
		menu.attachMenuItem();
		list.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					if(list.getSelectedIndex()>=0)
						menu.showEntryMenu(e.getComponent(), e.getX(), e.getY());
					else
						menu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					if(list.getSelectedIndex()>=0)
						menu.showEntryMenu(e.getComponent(), e.getX(), e.getY());
					else
						menu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
			
			@Override
			public void mouseExited(MouseEvent e) {
				AWTUtilities.setWindowOpacity(frame, 0.37f);
				list.clearSelection();
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				AWTUtilities.setWindowOpacity(frame, 0.75f);
				int index = list.locationToIndex(e.getPoint());
				list.setSelectedIndex(index);
			}

			@Override
			public void mouseClicked(MouseEvent e) {
			}
		});
		return list;
	}

	private Vector<Goal> getGoalList() {
		Vector<Goal> vector;
//		vector = new Vector<Goal>(3);
//		vector.add(new Goal(0, "title 1", "description 1"));
//		vector.add(new Goal(1, "title 2", "description 2"));
//		vector.add(new Goal(2, "title 2", "description 3"));
		vector = new Vector<Goal>(Globals.dbService.getGoalList());
		return vector;
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new MainUI();
			}
		});
	}

}
